{% extends "base.html" %}

{% block title %}课堂行为知识图谱 - 智慧课堂分析系统{% endblock %}

{% block content %}
<h2>课堂行为知识图谱</h2>
<p>可视化展示学生、行为和课程之间的关联关系</p>

<div class="toolbar" style="padding:10px 12px; border-bottom:1px solid #eaeaea; display:flex; flex-wrap:wrap; gap:10px; align-items:center; margin-bottom: 20px;">
    <label>课程：</label>
    <select id="classSelect" style="padding: 6px 8px;"><option value="">全部</option></select>
    <label>老师：</label>
    <select id="teacherSelect" style="padding: 6px 8px;"><option value="">全部</option></select>
    <label>班级：</label>
    <select id="classNameSelect" style="padding: 6px 8px;"><option value="">全部</option></select>
    <label>学生关键词：</label>
    <input type="text" id="studentInput" placeholder="如：张三" style="padding: 6px 8px;" />
    <label>日期：</label>
    <input type="text" id="dateInput" placeholder="YYYY-MM-DD" style="padding: 6px 8px;" />
    <label>行为类型：</label>
    <div class="behaviors" id="behaviorBox" style="display:flex; gap:8px; flex-wrap:wrap; max-height:72px; overflow:auto;"></div>
    <button id="searchBtn" style="padding: 6px 12px; background-color: #007bff; color: white; border: none; border-radius: 4px; cursor: pointer;">查询</button>
    <button id="pdfBtn" style="padding: 6px 12px; background-color: #28a745; color: white; border: none; border-radius: 4px; cursor: pointer;">导出PDF</button>
</div>

<div id="mynet" style="width:100%; height: 600px; border: 1px solid #ddd; border-radius: 5px; background: #f8f9fa;"></div>

<script src="https://unpkg.com/vis-network/standalone/umd/vis-network.min.js"></script>
<script>
let network = null;
let behaviorTypes = [];

function buildParams() {
    const params = new URLSearchParams();
    const classId = document.getElementById('classSelect').value;
    const teacher = document.getElementById('teacherSelect').value;
    const className = document.getElementById('classNameSelect').value;
    const studentKw = document.getElementById('studentInput').value.trim();
    const dateVal = document.getElementById('dateInput').value.trim();
    if (classId) params.set('class_id', classId);
    if (teacher) params.set('teacher', teacher);
    if (className) params.set('class_name', className);
    if (studentKw) params.set('student', studentKw);
    if (dateVal) params.set('date', dateVal);
    const checked = Array.from(document.querySelectorAll('#behaviorBox input[type=checkbox]:checked')).map(x => x.value);
    checked.forEach(v => params.append('behavior_types', v));
    return params;
}

function loadFilters() {
    fetch('{{ url_for("knowledge_graph.filters") }}').then(r => r.json()).then(f => {
        // classes
        const cs = document.getElementById('classSelect');
        (f.classes || []).forEach(c => {
            const opt = document.createElement('option');
            opt.value = c.id; opt.textContent = `${c.id} - ${c.name || ''}`;
            cs.appendChild(opt);
        });
        // teachers
        const ts = document.getElementById('teacherSelect');
        (f.teachers || []).forEach(t => {
            const opt = document.createElement('option');
            opt.value = t.teacher || ''; opt.textContent = t.teacher || '';
            ts.appendChild(opt);
        });
        // class names
        const cns = document.getElementById('classNameSelect');
        (f.class_names || []).forEach(cn => {
            const opt = document.createElement('option');
            opt.value = cn.className || ''; opt.textContent = cn.className || '';
            cns.appendChild(opt);
        });
        // behaviors
        behaviorTypes = (f.behaviors || []).map(b => b.type).filter(Boolean);
        const box = document.getElementById('behaviorBox');
        box.innerHTML = '';
        behaviorTypes.forEach(t => {
            const id = 'bh_' + t;
            const lab = document.createElement('label'); lab.htmlFor = id; lab.style.marginRight = '8px';
            const cb = document.createElement('input'); cb.type = 'checkbox'; cb.id = id; cb.value = t;
            lab.appendChild(cb); lab.appendChild(document.createTextNode(' ' + t));
            box.appendChild(lab);
        });
        // quick helpers
        const allBtn = document.createElement('button'); 
        allBtn.textContent = '全选'; 
        allBtn.type = 'button'; 
        allBtn.style.padding = '4px 8px';
        allBtn.onclick = ()=>{
            document.querySelectorAll('#behaviorBox input[type=checkbox]').forEach(x=>x.checked=true);
        };
        const clrBtn = document.createElement('button'); 
        clrBtn.textContent = '清空'; 
        clrBtn.type = 'button'; 
        clrBtn.style.padding = '4px 8px';
        clrBtn.onclick = ()=>{
            document.querySelectorAll('#behaviorBox input[type=checkbox]').forEach(x=>x.checked=false);
        };
        box.appendChild(allBtn); 
        box.appendChild(clrBtn);
    }).catch(error => {
        console.error('加载筛选条件失败:', error);
        alert('加载筛选条件失败，请刷新页面重试');
    });
}

function loadGraph() {
    const params = buildParams();
    fetch('{{ url_for("knowledge_graph.data") }}?' + params.toString())
        .then(r => r.json())
        .then(data => {
            // 创建节点和边的数据
            const nodes = new vis.DataSet(data.nodes || []);
            const edges = new vis.DataSet(data.edges || []);
            
            // 配置
            const container = document.getElementById('mynet');
            const options = {
                nodes: {
                    shape: 'box',
                    margin: 10,
                    font: { size: 14, face: 'Arial' },
                    color: {
                        background: ['#97C2FC', '#B6E3F4', '#FFD89B'],
                        border: '#2B7CE9'
                    },
                    shadow: true
                },
                edges: {
                    width: 2,
                    color: { color: '#848484' },
                    font: { size: 12, align: 'middle' }
                },
                physics: {
                    forceAtlas2Based: {
                        gravitationalConstant: -26,
                        centralGravity: 0.005,
                        springLength: 230,
                        springConstant: 0.18
                    },
                    maxVelocity: 146,
                    solver: 'forceAtlas2Based',
                    timestep: 0.35,
                    stabilization: { iterations: 150 }
                }
            };
            
            // 创建网络
            if (network) {
                network.destroy();
            }
            network = new vis.Network(container, { nodes, edges }, options);
            
            // 添加点击事件
            network.on('click', function(params) {
                if (params.nodes.length > 0) {
                    const nodeId = params.nodes[0];
                    const node = nodes.get(nodeId);
                    console.log('节点点击:', node);
                    // 可以在这里添加点击节点后的操作
                }
            });
        })
        .catch(error => {
            console.error('加载图谱数据失败:', error);
            alert('加载图谱数据失败，请检查数据库连接或刷新页面重试');
        });
}

function exportPDF() {
    const params = buildParams();
    window.location.href = '{{ url_for("knowledge_graph.report_pdf") }}?' + params.toString();
}

// 初始化
window.onload = function() {
    loadFilters();
    
    // 搜索按钮点击事件
    document.getElementById('searchBtn').onclick = loadGraph;
    
    // PDF导出按钮点击事件
    document.getElementById('pdfBtn').onclick = exportPDF;
};
</script>

<style>
    .toolbar label {
        margin-right: 6px;
        font-size: 13px;
        color: #333;
    }
    .toolbar input, .toolbar select {
        font-size: 13px;
        padding: 6px 8px;
    }
    .behaviors {
        display: flex;
        gap: 8px;
        flex-wrap: wrap;
        max-height: 72px;
        overflow: auto;
    }
</style>
{% endblock %}